// ==OrangeExtension==
// @name ncatapp
// @version v0.0.1
// @author orange
// @lang zh-cn
// @icon https://61.147.93.252:15001/vod_pc_static_ncat/images/favicon.ico
// @package com.ncat3.www
// @type tv
// @webSite https://www.ncat3.com:51111/
// ==/OrangeExtension==

import Extension from '../Extension'
import { Detail, ListItem, Episode } from '../interfaces/types'

class App extends Extension {
    coverUrl: string
    constructor(url: string) {
        super(url)
        this.coverUrl = "https://61.147.93.252:15002"
    }
    //最近更新
    async latest(page?: number) {
        let novel: {
            isNext: boolean,
            list: ListItem[]
        } = {
            isNext: false, // 初始设置
            list: [] // 初始化list
        };
        const res = await this.request(`${this.url + (page ? `/new/${page}.html` : "new/1.html")}`);

        if (res) {
            const dcm = this.setHtml(res)
            let moudle_item = dcm.querySelector(".module-box-inner")?.children
            let isNext = dcm.querySelector(".page-item-next") ? true : false
            if (moudle_item)
                for (const ele of moudle_item) {
                    novel.isNext = isNext
                    novel.list.push({
                        cover: this.coverUrl + ele.querySelector("a > div > div > img")?.getAttribute('data-original'),
                        title: ele.querySelector("a > div > div > img")?.getAttribute('title') ?? "APIError",
                        url: this.url + ele.querySelector("a")?.getAttribute("href"),
                    })
                }
        }
        return novel;
    }
    async detail(url: string) {
        const getActors = (node: Element | null): string => {
            if (node) {
                let actors = ""
                let mchildren = node.querySelector("div:nth-child(2)")?.children

                if (mchildren)
                    for (const ele of mchildren) {
                        actors += (ele?.textContent ?? "") + "/"
                    }

                return actors.substring(0, actors.length - 1)
            }
            return ""
        }
        let novel: Detail = {
            title: "",
            cover: "",
        }
        let espArr: Episode[] = []

        const res = await this.request(url);

        if (res) {
            const dcm = this.setHtml(res)
            const title = dcm.querySelector(".detail-title > strong")?.textContent?.trim() ?? ""
            const cover = this.coverUrl + (dcm.querySelector(".detail-pic > img")?.getAttribute("data-original") ?? "")
            const desc = dcm.querySelector(".detail-desc > p")?.textContent?.trimStart().trimEnd() ?? ""
            let descInfo = dcm.querySelectorAll('.detail-info-row')
            //添加元数据
            const metadata = {
                director: descInfo[0]?.querySelector("div:nth-child(2) > a")?.textContent ?? "",
                actors: getActors(descInfo[1]),
                time: descInfo[2]?.querySelector("div:nth-child(2)")?.textContent ?? "",
                mark: descInfo[3]?.querySelector("div:nth-child(2)")?.textContent ?? "",
            }
            //处理线路和选集
            let lineItems = dcm.querySelector(".source-box .swiper-wrapper")?.children
            let lineEpisodeItems = dcm.querySelector(".episode-box-main")?.children
            let eleIndex = 0
            if (lineItems && lineEpisodeItems)
                for (const ele of lineItems) {
                    let lineName = ele.querySelector('div > a > span')?.textContent ?? ""
                    let tmpObj = []
                    let episodeChildren = lineEpisodeItems[eleIndex]?.children
                    if (episodeChildren) {
                        for (const esp of episodeChildren) {
                            let alink = this.url + esp.getAttribute("href") ?? ""
                            let espName = esp.textContent ?? ""
                            tmpObj.push({ name: alink, url: espName })

                        }
                        espArr.push({
                            title: lineName,
                            urls: tmpObj
                        })
                    }
                    eleIndex++;
                }
            //添加数据
            novel = {
                title,
                cover,
                desc,
                metadata,
                episodes: espArr
            }
        }
        return novel
    }
    async search(kw: string, page?: number) {
        const res = await this.request(`${this.url}/search?k=${encodeURIComponent(kw)}&page=${page ? page : 1}`);
        const novel: ListItem[] = [];
        if (res) {
            const dcm = this.setHtml(res)
            let searchResult = dcm.querySelector(".search-result-list")?.children
            if (searchResult) {
                for (const ele of searchResult) {
                    let url = this.url + (ele.getAttribute("href") ?? "")
                    let cover = this.coverUrl + (ele.querySelector("div.search-result-item-ctn img")?.getAttribute("data-original") ?? "")
                    let title = ele.querySelector("div.search-result-item-main > .title")?.textContent ?? ""
                    novel.push({
                        title,
                        url,
                        cover
                    })
                }
            }
        }

        return novel;
    }
    async watch(url: string) {
        const res = await this.request(url);
        let _url = res?.match(/src:\s*"(.+)"/)
        return {
            type: "hls",
            url: _url && _url[1] || "",
        };
    }
}

export default App

// ; (async () => {
//     const appInstance = new App("https://www.ncat3.com:51111")
//     let espinfo = await appInstance.watch("https://www.ncat3.com:51111/play/170530-34-295727.html")
//     console.log(espinfo);
//     console.log("done");

// })();

